Ext.ns('ru.proburo.oms.air');

/**
 * ru.proburo.oms.air.Activator
 * @extends ru.proburo.oms.module.AbstractActivator
 */
ru.proburo.oms.air.Activator = Ext.extend(ru.proburo.oms.module.AbstractActivator, {
    
	_monitor: 		  	 null,
	_monitorInterval: 	 10000, // microseconds
	
	_autoUpdater: 	  	 null,
	_autoUpdateUrl:   	 ru.proburo.oms.Constants.URL + '/updates/update.xml',
	_autoUpdateInterval: 1, // days
	
	_loggedIn: 	  	     false,
    
    start: function(viewport)
    {
        this.viewport = viewport;
        
        var tbar = viewport.layout.north.panel;
		
        this.tbar = tbar;
        
		this.statusLabel = tbar.insert(0, {xtype:'tbtext', text: 'Нет подключения'});
        this.statusIcon  = tbar.insert(0, {xtype:'tbtext', text: '&nbsp;&nbsp;&nbsp;&nbsp;'});
        
		// TODO: move to components
        this.loginAction = tbar.addItem({
            xtype:   'button',
            text:    'Войти',
            iconCls: 'silk-key',
            disabled: true,
            listeners: {
                click: this._showLoginForm,
                scope: this
            }
        });
        this.tbar.doLayout();
        
        this._initMonitor();
		this._initAutoUpdate();
    },
	
	// private
    _initMonitor: function()
    {
        var request = new air.URLRequest(ru.proburo.oms.Constants.URL);
        request.method = 'HEAD';
        
        this._monitor = new air.URLMonitor(request);
        this._monitor.pollInterval          = this._monitorInterval;
        this._monitor.acceptableStatusCodes = [200, 401];
        
		var that = this;
		
		this._monitor.addEventListener(air.StatusEvent.STATUS, function(e){
            that._onServiceStatusChange(e);
        });
		
        this._monitor.start();
    },
    // private
    _initAutoUpdate: function()
	{
		this._autoUpdater = new runtime.air.update.ApplicationUpdaterUI();
		
		this._autoUpdater.updateURL = this._autoUpdateUrl; 
		this._autoUpdater.delay 	= this._autoUpdateInterval;
		
		this._autoUpdater.initialize();
	},
	
    setStatusIcon: function(iconCls)
    {
        this.statusIcon.removeClass(this._currentIconCls);
        this.statusIcon.addClass(iconCls);
        
        this._currentIconCls = iconCls;
    },
    
    _showLoginForm: function(button, e){
        this._form = new Ext.FormPanel({ 
            title:        'Авторизация',
            iconCls:      'silk-brick', 
            url:          'http://client.proburo.ru/login', 
            frame:        true, 
            labelWidth:   68,
            monitorValid: true,
            defaultType: 'textfield',
            buttonAlign: 'center',
            items:
            [
                { 
                    name: 'u', 
                    fieldLabel: 'Логин',
					value: 'zhuravlev',
                    allowBlank: false,
                    listeners:
                    {
                        specialkey: this._onSpecialKey,
                        scope:      this
                    }
                },
                { 
                    name: 'p', 
                    fieldLabel: 'Пароль',
					value: 'spyieo0z',
                    allowBlank: false,
                    inputType: 'password',
                    listeners:
                    {
                        specialkey: this._onSpecialKey,
                        scope:      this
                    }
                }
            ],
            buttons: [{
                text:     'Войти',
                handler:  this._doLogin,
                formBind: true,
                scope:    this
            },
            {
                text:     'Отмена',
                handler:  this._doClose,
                scope:    this
            }]
        });
        
        
        this._win = new Ext.Window({
            layout: 'fit',
            width: 273,
            height: 142,
            closable: false,
            resizable: false,
            plain: false,
            border: false,
            items: [this._form]
        });
        this._win.show();
    },
	
	/**
	 * Action handlers
	 */
	// private
    _doLogin: function()
    {
        this._form.getForm().submit({ 
            method: 'POST', 
            success: this._onLoginSuccess,
			failure: this._onLoginFailure,
            scope:   this
        });
    },
    // private
    _doLogout: function()
    {
        console.log(document.cookie);
    },
    // private
    _doClose: function()
    {
        this._win.destroy();
    },
	
	
	
	/**
	 * Listeners
	 */
	// private
    _onServiceStatusChange: function(e)
    {
        if(true === this._monitor.available)
        {
            this.setStatusIcon('silk-bullet-green');
            this.statusLabel.setText('В сети');
        }
        else
        {
            this.setStatusIcon('silk-bullet-red');
            this.statusLabel.setText('Нет подключения');
        }
        this.loginAction.setDisabled(!this._monitor.available && !this._loggedIn);
    },
	// private
    _onSpecialKey: function(field, el)
    {
        if (el.getKey() == Ext.EventObject.ENTER)
        {
            this._doLogin();
        }
    },    
    // private
    _onLoginSuccess: function()
    {
        this._loggedIn = true;
        
        var sync = new ru.proburo.oms.air.dao.SyncManager();        
        sync.on({
            complete:  this._onSyncComplete,
            exception: this._onSyncException,
            scope:     this
        });
        sync.synchronize();
        
        this.loginAction.hide();
		this._doClose();
    },
    // private
    _onLoginFailure: function()
    {
        console.warn('Authorization failed.');
    },
	// private
    _onSyncComplete: function()
    {
        this.viewport.catTree.getRootNode().reload(function(){});
    },
	// private
    _onSyncException: function()
    {
        this.loginAction.show();
    }    
});
ru.proburo.oms.Bootstrap.reg(ru.proburo.oms.air.Activator);